package com.jd.controller;

import com.jd.bean.*;
import com.jd.service.*;
import com.jd.utils.uuid.IdUtils_8;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/lma")
public class LMAController {
    public String loaNo = "";
    public Company company = null;

    @Autowired
    private ILoansService loansService;

    @Autowired
    private IMaterialsService materialsService;

    @Autowired
    private IBankService bankService;

    @Autowired
    private IAptitudeService aptitudeService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private IComDetailsService comDetailsService;

    @Autowired
    private IRefundService refundService;

    @Autowired
    private IOverdueService overdueService;


    /**
     * 公司信息
     *
     * @return
     */
    @RequestMapping()
    public String insertLoansForm(HttpServletRequest request, String loaDown, Model model, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String pNo = (String) request.getSession().getAttribute("users");
//        company = companyService.selectCompanyLoginTel(pNo);
        if (!(pNo == null)) {
            //判断是邮箱还是手机号的正则表达式
            String em = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
            String ph = "^[1][34578]\\d{9}$";
            if (pNo.matches(em)) {
                company = companyService.selectCompanyLoginEma(pNo);
            } else if (pNo.matches(ph)) {
                company = companyService.selectCompanyLoginTel(pNo);
            }
            //查询逾期信息
            model.addAttribute("overdueAll", overdueService.selectOverdueComId(String.valueOf(company.getComId())));
//            查询签约信息
            model.addAttribute("sign", loansService.selectLoansSign(String.valueOf(company.getComId())));
            //查询原密码
            model.addAttribute("editPsw", company.getComPwd());
            //查询还款信息
            model.addAttribute("refundMessage", refundService.selectRefundListAll(String.valueOf(company.getComId())));
            //还款记录
            model.addAttribute("refundMegLog", refundService.selectRefundLog(String.valueOf(company.getComId())));
//            System.out.println(refundService.selectRefundLog(String.valueOf(company.getComId())));
            ComDetails comDetails = comDetailsService.selectComDetailsByCId(Long.valueOf(company.getComId()));
            if (!(comDetails == null)) {
                model.addAttribute("comDetails", comDetails);
                model.addAttribute("loaCount", loansService.selectLoansCount(String.valueOf(company.getComId())));
            } else {
                Provinces p = new Provinces();
                Cities c = new Cities();
                ComDetails com = new ComDetails(company, p, c);
                model.addAttribute("comDetails", com);
                model.addAttribute("loaCount", 0);
            }
            List<Loans> loansComList = loansService.selectLoansByComList(String.valueOf(company.getComId()));
            if (loansComList.isEmpty()) {
                model.addAttribute("loansLog", 0);
            }
        } else {
            out.print("<script language=\"javascript\">alert('账号失效请重新登录');window.location.href='/login'</script>");
        }

        return loaDown;
    }


    /**
     * 提交贷款表
     *
     * @param loans
     * @return
     */
    @RequestMapping("/loans")
    @ResponseBody
    public String insertLoansForm(Loans loans, HttpServletRequest request) {
        String pNo = (String) request.getSession().getAttribute("users");
        company = companyService.selectCompanyLoginTel(pNo);
        //判断是邮箱还是手机号的正则表达式
        String em = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
        String ph = "^[1][34578]\\d{9}$";
        if (pNo.matches(em)) {
            company = companyService.selectCompanyLoginEma(pNo);
        } else if (pNo.matches(ph)) {
            company = companyService.selectCompanyLoginTel(pNo);
        }
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String d = dateFormat.format(date);
//        生成企业编号
        loaNo = IdUtils_8.getUUID_8() + d;
        loans.setLoaNo(loaNo);
//        贷款表创建时间
        loans.setLoaTime(date);
        loans.setLoaComNo(String.valueOf(company.getComId()));
//        int i = 1;
        int i = loansService.insertLoans(loans);
        if (i > 0) {
            return "ok";
        } else {
            return "ng";
        }
    }

    /**
     * 实名认证
     *
     * @param request
     * @param comDetails
     * @return
     * @throws Exception
     */
    @RequestMapping("/att")
    @ResponseBody
    public boolean attCompany(MultipartHttpServletRequest request, ComDetails comDetails) {
        //获取上传的图片
        List<MultipartFile> files = request.getFiles("file");
        //无文件时直接返回页面
        if (files == null || files.isEmpty()) {
            return false;
        }
        //将企业Id存入详情表
        comDetails.setCoId(Long.valueOf(company.getComId()));
        //修改认证状态
        companyService.updateCompanyAttState(company.getComId());
        return comDetailsService.attCompanies(comDetails, files);
    }


    /*@RequestMapping( "/listWater")
    @ResponseBody
    public boolean addMaterials(Materials materials,@RequestParam("fileImg") MultipartFile fileImg) throws UnsupportedEncodingException {
        String filename = URLEncoder.encode(fileImg.getOriginalFilename(), "utf-8");
        System.out.println("获取对象"+fileImg.getOriginalFilename());

//        UploadUtils.doFileUpload(fileImg, materials, "lisSixRunWater");

            materialsService.insertMaterials(materials);
        return true;
    }*/

    /**
     * 提交材料表
     *
     * @param request
     * @param materials
     * @return
     * @throws Exception
     */
    @RequestMapping("/listWater")
    @ResponseBody
    public boolean addMaterials(MultipartHttpServletRequest request, Materials materials) {
        //获取贷款ID
        Long s = loansService.selectLoansByNo(loaNo);
        materials.setLisLoaId(s);
        materials.setLisComId(Long.valueOf(company.getComId()));
        List<MultipartFile> files = request.getFiles("file");
        //无文件时直接返回页面
        if (files == null || files.isEmpty()) {
            return false;
        }
        return materialsService.insert(materials, files);
    }

    /**
     * 提交资质表
     *
     * @param aptitude
     * @return
     */
    @RequestMapping("/apt")
    @ResponseBody
    public boolean insertAptForm(Aptitude aptitude) {
        aptitude.setAptLoaId(loansService.selectLoansByNo(loaNo));
        aptitude.setComId(Long.valueOf(company.getComId()));
        int i = 0;
        i = aptitudeService.insertAptitude(aptitude);
        if (i > 0) {
            return true;
        } else {
            return false;
        }
    }


    @RequestMapping("/materials")
    @ResponseBody
    public String insertMaterialsForm(Materials materials, MultipartFile upFile[], HttpServletRequest request) throws IOException {
//        1.上传文件到 服务器的upload的文件夹
        String uploadPath = "upload";
        //上传实际位置
        String path = request.getSession().getServletContext().getRealPath(uploadPath);
        //使用逗号隔开
        StringBuffer stringBuffer = new StringBuffer();
        for (MultipartFile file : upFile) {
            if (!file.isEmpty()) {
                //为了避免文件重复
                stringBuffer.append(file.getOriginalFilename());
                stringBuffer.append(",");

                File filePath = new File(path, file.getOriginalFilename());
                if (!filePath.exists()) {
                    //创建目录
                    filePath.mkdirs();
                }
                file.transferTo(filePath);
            }
        }

        if (stringBuffer.length() > 0) {
            materials.setLisPawn(uploadPath);
            int i = 1;
//                    materialsService.insertMaterials(materials);
            System.out.println("i" + i);
            if (i > 0) {
                return "ok";
            } else {
                return "ng";
            }
        } else {
            return "ng";
        }
    }


    @RequestMapping("/upload")
    @ResponseBody
    public String uploadForm(MultipartFile upFile[], HttpServletRequest request) throws IOException {
//        1.上传文件到 服务器的upload的文件夹
        String uploadPath = "upload";
        //上传实际位置
        String path = request.getSession().getServletContext().getRealPath(uploadPath);
        //使用逗号隔开
        StringBuffer stringBuffer = new StringBuffer();
        for (MultipartFile file : upFile) {
            if (!file.isEmpty()) {
                //为了避免文件重复
                stringBuffer.append(file.getOriginalFilename());
                stringBuffer.append(",");

                File filePath = new File(path, file.getOriginalFilename());
                if (!filePath.exists()) {
                    //创建目录
                    filePath.mkdirs();
                }
                file.transferTo(filePath);
            }
        }

        return "ng";
    }

    /**
     * 查询银行列表
     *
     * @return
     */
    @RequestMapping("/banks")
    @ResponseBody
    public List<Bank> findBankAll() {
        List<Bank> bankList = bankService.selectBankNames();
        return bankList;
    }

    /**
     * 查询贷款列表
     *
     * @return
     */
    @RequestMapping("/queryLoans")
    @ResponseBody
    public List<Loans> findLoansAll() {
        List<Loans> loansComList = loansService.selectLoansByComList(String.valueOf(company.getComId()));
        return loansComList;
    }


    /**
     * 查询贷款进度
     *
     * @return
     */
    @RequestMapping("/loansPlan")
    @ResponseBody
    public List<Loans> findLoansPlan(int loaId) {
        List<Loans> loansPlan = loansService.selectLoansPlanList(loaId);
        return loansPlan;
    }

    /**
     * 查询利率
     *
     * @param bId
     * @return
     */
    @RequestMapping("/rateById")
    @ResponseBody
    public String findBankRate(Long bId) {
        return bankService.selectBankRateById(bId);
    }

    /**
     * 修改密码
     *
     * @return
     */
    @RequestMapping("/editPsw")
    @ResponseBody
    public boolean editPswCompanyById(String psw) {
        int i = companyService.updateCompanyPsw(company.getComId(), psw);
        if (i > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 银行信息
     *
     * @return
     */
    @RequestMapping("/bankSign")
    @ResponseBody
    public Bank findBankMessage(Long bId) {
        return bankService.selectBankByBankId(bId);
    }


    /**
     * 判断是否实名认证
     *
     * @return
     */
    @RequestMapping("/queryAtt")
    @ResponseBody
    public boolean queryCompanyAtt() {
        if (company.getComStatus().equals("3")){
            return true;
        }else {
            return false;
        }
    }

}
